package com.wyq.new_springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wyq.new_springboot.NewSpringbootApplication;
import com.wyq.new_springboot.config.MyException;
import com.wyq.new_springboot.constant.LogAction;
import com.wyq.new_springboot.constant.LoginState;
import com.wyq.new_springboot.dao.MyDao;
import com.wyq.new_springboot.entity.TLog;
import com.wyq.new_springboot.entity.TUser;
import com.wyq.new_springboot.mapper.TLogMapper;
import com.wyq.new_springboot.mapper.TUserMapper;
import com.wyq.new_springboot.service.ITLogService;
import com.wyq.new_springboot.service.ITUserService;
import com.wyq.new_springboot.util.MD5;
import com.wyq.new_springboot.util.result.Result;
import com.wyq.new_springboot.util.result.ResultCode;
import com.wyq.new_springboot.util.result.ResultGenerator;
import com.wyq.new_springboot.util.result.ResultMessage;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.*;

@org.springframework.stereotype.Controller
@RequestMapping("/test")
public class Controller {
    private static final Logger LOGGER = LoggerFactory.getLogger(Controller.class);
    @Autowired
    ITUserService itUserService;
    @Autowired
    ITLogService itLogService;
    @RequestMapping("/testException")
    public Result testException(Model model){
//        Object author = model.getAttribute("author");
//        System.out.println(author.toString());
//        int s=1/0;
        throw new MyException("自定义异常");
//        return null;
    }
    @RequestMapping("/noAuth")
    public String toNoAuth(){
        return "noAuth";
    }
    /**
     * 跳到主页
     * @param model
     * @return
     */
    @RequestMapping("/index")
    public String toPage(Model model){
        List<TLog> tLogs = itLogService.selectLimit(6, "create_time");
        model.addAttribute("logs",tLogs);
        return "index";
    }

    /**
     * 如果是注册页面，增加标识
     * @param model
     * @return
     */
    @RequestMapping("/register")
    public String register(Model model){
        model.addAttribute("state", LoginState.REGISTER_TYPE.getStateName());
        return "login";
    }
    /**
     * 登录页面
     * @param model
     * @return
     */
    @RequestMapping("/login")
    public String login(Model model){
        return "login";
    }
    /**
     * 处理注册
     * @param userName
     * @param password
     * @param email
     * @return
     */
//    @RequiresRoles("admin")
    @RequestMapping("/doRegister")
    @ResponseBody
    public Result doRegister(@RequestParam String userName,
                             @RequestParam String password,
                             @RequestParam String email){
        TUser tUser=new TUser(null,userName,password,email);
        try {
            String userpassword = MD5.EncoderByMd5(password);
            tUser.setUserPassword(userpassword);
            itUserService.insert(tUser);
            return ResultGenerator.genSuccessResult();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 处理登录请求
     * @param model
     * @param request
     * @param response
     * @param userName
     * @param password
     * @return
     */
//    @RequiresRoles("admin")
    @RequestMapping("/userLogin")
    @ResponseBody
    public Result login(Model model,
                        HttpServletRequest request,
                        HttpServletResponse response,
                        @RequestParam String userName,
                        @RequestParam String password){
        Subject subject = SecurityUtils.getSubject();
        LOGGER.debug("登陆了成功------------------");
        LOGGER.info("登陆了成功------------------");
        Map<String,Object> map=new HashMap<>();
        map.put("user_name",userName);
        String user_password = null;
        Result result=new Result();
        try {
            user_password = MD5.EncoderByMd5(password);
            map.put("user_password",user_password);
            //认证
            UsernamePasswordToken usernamePasswordToken =
                    new UsernamePasswordToken(userName, user_password);
            subject.login(usernamePasswordToken);
            List<TUser> list = itUserService.selectByMap(map);
            if(list.size()>0){
                TUser tUser = list.get(0);
                String userName1 = tUser.getUserName();
                Cookie cookie=new Cookie("userName",userName1);
                cookie.setPath("/");
                response.addCookie(cookie);
                //设置session
                request.getSession().setAttribute("user",tUser);
                TLog tLog=new TLog(null, LogAction.BEND.getActionName(),String.valueOf(tUser.getId()),request.getRemoteAddr(), LocalDateTime.now());
                itLogService.insert(tLog);
                result=ResultGenerator.genSuccessResult();
            }else {
                result=ResultGenerator.genFailResult(ResultCode.FAIL, ResultMessage.FAIL.getMessage());
            }
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }



}
